package com.pet.service.impl;

import com.pet.dao.PictureDAO;
import com.pet.entity.dos.PictureDO;
import com.pet.entity.dto.PicQueryDTO;
import com.pet.entity.vo.PicTagVO;
import com.pet.service.PictureService;
import com.pet.utils.AliOSSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class PictureServiceImpl implements PictureService {

    @Autowired
    private PictureDAO pictureDAO;

    @Autowired
    private AliOSSUtils aliOSSUtils;
    @Override
    public List<PictureDO> queryPicture(PicQueryDTO pic) {
        return pictureDAO.selectPictureList(pic);
    }

    @Override
    public Integer countPicture(PicQueryDTO pic) {
        return pictureDAO.countPictureList(pic);
    }

    @Override
    public List<PicTagVO> queryPicTag() {
        return pictureDAO.selectTagPicList();
    }

    @Override
    public PictureDO upload(String detail, String tag, MultipartFile file) throws IOException {

        // 1. 获取原始文件名
        String oldFileName = file.getOriginalFilename();
        // 2. 构建新的文件名
        String fileName = UUID.randomUUID().toString() + oldFileName.substring(oldFileName.lastIndexOf(".")) ;
        // 3. 将文件保存在阿里云中
        String url = aliOSSUtils.upload(tag, file);
        // 4. 检验是否插入成功
        boolean check = aliOSSUtils.isExistedOSSFile(url);
        if(!check) return null;
        // 4. 调用业务层，实现插入
        else {
            PictureDO pictureDO = new PictureDO();
            pictureDO.setDetail(detail);
            pictureDO.setTag(tag);
            pictureDO.setImgUrl(url);
            pictureDO.setCreateTime(new Date());
            return pictureDAO.insert(pictureDO) ? pictureDO : null;
        }
    }
}
